import React, { useEffect, useRef, useState } from 'react';
import { connect, history } from 'umi';
import { Alert, Button, Space, Tag, Modal, notification, Row, Col, Checkbox } from 'antd'
import TableDataBlock from '@/components/TableDataBlock';
import RoleSetForm from './components/SetForm';
import CodeModel from './components/CodeModel'
import PopImgShow from '@/components/PopImgShow';
import UpdateLevel from './components/updateLevel';
import UpdateShare from './components/updateShare';
import SearchCondition from '@/components/SearchCondition';
import CodeShare from './components/CodeShare'
import BankForm from './components/bankForm';
import BindAssign from './components/BindAssign'
import OriParentList from './components/OriParentList';
import { uploadFile } from '@/utils/utils';
import SelectPromoterGroup from '@/components/SelectPromoterGroup';
import request from 'axios';
const PromoterList = (props) => {
    const { loading, dispatch, list, zm } = props;
    const { location } = history
    const { query } = location
    const { accessId } = query
    const childRef = useRef();
    const [visible, setVisible] = useState(false);
    const [codeVisible, setCodeVisible] = useState(false)
    const [promoterLevelList, setPromoterLevelList] = useState([])
    const [levelVisible, setLevelVisible] = useState(false)
    const [initVisible, setInitVisible] = useState(false)
    const [shareVisible, setShareVisible] = useState(false)
    const [bankVisible, setBankVisible] = useState(false)
    const [oriVisible, setOriVisible] = useState(false)
    const [bindAssignVisible, setBindAssignVisible] = useState(false)
    const [promoterGroupVisible, setPromoterVisible] = useState(false)
    const [params, setSearchParams] = useState({})
    const [selectedRow, setSelectedRow] = useState({
        selectedRowKeys: [],
        type: 'checked',
        preserveSelectedRowKeys: true,
        onChange: (val, selectedRows) => {
            setSelectedRow({
                ...selectedRow,
                selectedRowKeys: val,
                rowKeyList: selectedRows
            });
        },

    });
    const importUserExcelTemplate = () => {
        uploadFile('https://resource.gy.cn/template/importPromoterExcelTemplate2-1720443859444.xlsx')
    }
    const inputFile = async () => {
        const options = {
            types: [
                {
                    description: 'Excel Files',
                    accept: {
                        'application/vnd.ms-excel': ['.xls'],
                        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx']
                    }
                }
            ],
            multiple: false
        };

        try {
            window.showOpenFilePicker(options).then(async val => {
                const [fileHandle] = val
                fileHandle.getFile().then(data => {
                    const formData = new FormData();
                    formData.append('file', data);
                    formData.append('token', window.localStorage.getItem('token'));
                    request.post(APIURL + '/promoter/importPromoter', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data',
                            appType: 'organization',
                            device: 'web',
                            Accept: 'application/json',
                        },
                    }).then(val => {
                        const { data = {},
                        } = val
                        const { resultCode, resultDesc, content = {} } = data
                        console.log(data)
                        if (resultCode === '1') {
                            const { url } = content
                            Modal.confirm({
                                title: '导入结果',
                                content: '用户导入已完成，点击下载查看导入结果',
                                okText: '下载',
                                onOk() {
                                    uploadFile(url)
                                },
                                onCancel() {
                                    console.log('Cancel');
                                },
                            })
                            handleCallback()
                        }
                        else {
                            notification.error({
                                message: `请求错误`,
                                description: resultDesc,
                            });
                        }

                    })
                })

            })
        } catch (error) {
            // 处理错误
            console.log(error)
        }
    }

    const fetchUrl = () => {
        dispatch({
            type: 'promoter/fetchActivityUrl',
            callback: (e) => {
                const { activityUrl } = e
                setCodeVisible({
                    show: true,
                    detail: {
                        url: activityUrl
                    }
                })
            }
        })
    }
    const fetchInitUrl = () => {
        dispatch({
            type: 'promoter/fetchGetInviteUrl',
            callback: (e) => {
                const { activityUrl } = e
                setInitVisible({
                    show: true,
                    detail: {
                        url: activityUrl
                    }
                })
            }
        })


    }
    const fetchLevelList = () => {
        dispatch({
            type: 'promoter/fetchPromoterSimpleLevelDetail',
            callback: (e) => {
                const { promoterLevelList } = e
                setPromoterLevelList(promoterLevelList)
            }
        })
    }


    const fakeExportPromoter = () => {
        dispatch({
            type: 'promoter/fakeExportPromoter',
            payload: {
                ...params
            },
            callback: (e) => {
                const { url } = e
                uploadFile(url)
            }
        })

    }
    const fakeSetGroupId = (payload) => {
        dispatch({
            type: 'promoter/fakeSetGroupId',
            payload: payload,
            callback: (e) => {
                handleCallback()
                setSelectedRow({
                    ...selectedRow,
                    selectedRowKeys: [],
                })
            }
        })
    }
    useEffect(() => { childRef.current.initData(); }, [params])
    useEffect(() => {
        fetchLevelList()
    }, [])
    // 搜索参数
    const searchItems = [
        {
            label: '级别',
            name: 'levelId',
            type: 'select',
            select: promoterLevelList,
            fieldNames: { label: 'levelName', value: 'id' },
        },
        {
            label: '邀请人',
            name: 'shareKeyword',

        },
        {
            label: '申请人',
            name: 'keyword',
            placeholder: "请输入申请人姓名/手机号"
        },
        {
            label: '申请时间',
            type: 'rangePicker',
            name: 'createStartTime',
            end: 'createEndTime',
        },
        {
            label: '状态',
            name: 'status',
            type: 'select',
            select: {
                0: '禁用',
                1: '启用'
            },

        },
        {
            label: '激活状态',
            name: 'activityFlag',
            type: 'select',
            select: {
                0: '未激活',
                1: '已激活'
            },

        },
        {
            label: '是否关联员工',
            name: 'assignAdminStatus',
            type: 'select',
            select: {
                0: '未绑定',
                1: '已绑定'
            },

        },
        {
            label: '关联员工',
            name: 'assignAdminId',
            type: 'user',


        },
        {
            label: '分组',
            name: 'groupId',
            type: 'promoterGroup',


        },
    ];

    // table 表头
    const getColumns = [
        {
            title: '申请姓名 ',

            dataIndex: 'applyUsername',
        },
        {
            title: '申请手机号 ',

            dataIndex: 'applyMobile',
        },
        {
            title: '分组',

            dataIndex: 'groupName',
        },
        {
            title: '等级',

            dataIndex: 'levelName',
        },

        // {
        //     title: '所属团队',

        //     dataIndex: 'planDesc',
        // },

        {
            title: '邀请人',

            dataIndex: 'parentUsername',
        },
        {
            title: '绑定员工',

            dataIndex: 'assignAdminNames',
        },
        {
            title: '累计邀约客户',

            dataIndex: 'inviteUserAmount',
        },
        {
            title: '累计邀请推广员（人）',

            dataIndex: 'invitePromoterAmount',
        },
        {
            title: '已结算收益（元）',

            dataIndex: 'settledCommission',
        },
        {
            title: '待结算收益(元)',

            dataIndex: 'toSettledCommission',
        },
        {
            title: '银行卡号',
            dataIndex: 'bankCard',
        },
        {
            title: '银行名称',
            dataIndex: 'bankName',
        },
        {
            title: ' 银行户名',
            dataIndex: 'bankAccount',
        },
        {
            title: '加入时间',
            dataIndex: 'createTime',
        },
        {
            title: '状态',
            dataIndex: 'status',
            render: (e) => {
                return { 0: '禁用', 1: '启用' }[e]
            }
        },

        {
            type: 'handle',
            width: 200,
            dataIndex: 'id',
            render: (val, record) => [
                {
                    auth: true,
                    title: '详情',
                    visible: record.activityFlag === '1',
                    click: () => {
                        history.push({
                            pathname: '/marketingModule/promoterDetail',
                            query: {
                                accessId,
                                id: val,

                            }
                        })
                    },
                },
                {
                    auth: true,
                    title: '设置银行卡号',
                    visible: record.activityFlag === '1',
                    click: () => {
                        setBankVisible({
                            show: true,
                            detail: record
                        })
                    },
                },
                {
                    auth: true,
                    title: '查看族谱',
                    visible: record.activityFlag === '1',
                    click: () => {
                        setOriVisible({
                            show: true,
                            detail: record
                        })
                    },
                },
                {
                    auth: true,
                    title: '绑定员工',
                    visible: record.activityFlag === '1',
                    click: () => {
                        dispatch({
                            type: 'promoter/fetchPromoterDetail',
                            payload: {
                                promoterId: val
                            },

                            callback: (e) => {
                                const { promoterDetail = {} } = e
                                setBindAssignVisible({
                                    show: true,
                                    detail: promoterDetail,
                                    type: 'one'
                                })
                            }
                        })
                    },
                },
                {
                    auth: true,
                    title: '禁用',
                    visible: record.status === '1' && record.activityFlag === '1',
                    click: () => {
                        dispatch({
                            type: 'promoter/fakeDisablePromoter',
                            payload: { id: val },
                            callback: () => {
                                handleCallback()
                            }
                        })
                    },
                },
                {
                    auth: true,
                    title: '启用',
                    visible: record.activityFlag === '0' && record.activityFlag === '1',
                    click: () => {
                        dispatch({
                            type: 'promoter/fakeEnablePromoter',
                            payload: { id: val },
                            callback: () => {
                                handleCallback()
                            }
                        })
                    },
                },
                {
                    auth: true,
                    title: '修改邀请人',
                    visible: record.activityFlag === '1',
                    click: () => {
                        setShareVisible({
                            show: true,
                            selectIdList: [val],
                            updateList: [record]
                        })
                    },
                },
                {
                    auth: true,
                    title: '修改等级',
                    visible: record.activityFlag === '1',
                    click: () => {
                        setLevelVisible({
                            show: true,
                            selectIdList: [val]
                        })
                    },
                },
                {
                    auth: true,
                    title: '设置分组',
                    visible: record.activityFlag === '1',
                    click: () => {
                        setPromoterVisible({
                            show: true,
                            selectIdList: [val]
                        })
                    },
                },
                {
                    auth: true,
                    title: '清退',
                    visible: record.activityFlag === '0',
                    click: () => {
                        Modal.confirm({
                            title: '确认清退',
                            content: '清退后，用户将不再是推广员身份，【绑定的客户】和【邀请推广员】以及【团队】关系全部解除。用户可根据招募规则再次申请成为推广员',
                            okText: '确认',
                            onOk() {
                                dispatch({
                                    type: 'promoter/fakeRemoveUnActivityPromoter',
                                    payload: { id: val },
                                    callback: () => {
                                        handleCallback()
                                    }
                                })
                            },
                            onCancel() {
                                console.log('Cancel');
                            },
                        })
                    },
                },
            ],
        },
    ];
    const handleCallback = () => {
        childRef.current.fetchGetData();
    };
    const handleSaveRole = (detail = {}) => {
        setVisible({
            show: true,
            detail,
        });
    };


    return (

        <div>
            <Row gutter={[36, 12]}>
                <Col span={24}> <Alert type="warning" message={<div>需激活账号后才可成为推广员<Button onClick={() => fetchUrl()} type='link'>引导激活账户</Button></div>}></Alert></Col>
                <Col span={24}>
                    <Space size={'large'}>
                        <Button onClick={() => {
                            handleSaveRole();
                        }}>添加推广员</Button>
                        <Button type='primary' onClick={() => {
                            zm()
                        }}>招募推广员</Button>
                        <Button type='primary' onClick={() => {
                            fakeExportPromoter();
                        }}>导出推广员</Button>
                        <Button type='primary' onClick={() => {
                            fetchInitUrl();
                        }}>邀请推广员</Button>
                        <Button type='primary' onClick={() => inputFile()}>导入推广员</Button>
                        <Button type='link' onClick={() => importUserExcelTemplate()}>下载导入模板</Button>
                    </Space>
                </Col>
                <Col span={24}>
                    <div style={{ background: '#f5f5f5', padding: 24 }}>
                        <SearchCondition
                            handleSearch={(e) => {
                                setSearchParams(e);
                            }}
                            searchItems={searchItems}
                        ></SearchCondition>
                    </div>
                </Col>
                <Col span={24}>
                    <Space>
                        <Checkbox checked={selectedRow.selectedRowKeys.length === list.list.length} onChange={(e) => {
                            if (e.target.checked) {
                                setSelectedRow({
                                    ...selectedRow,
                                    selectedRowKeys: list.list.map(item => {
                                        return item.id.toString()
                                    }),
                                    rowKeyList: list.list
                                })
                            } else {
                                setSelectedRow({
                                    ...selectedRow,
                                    selectedRowKeys: [],
                                    rowKeyList: []
                                })
                            }

                        }}>当页全选</Checkbox>
                        <div>已选{selectedRow.selectedRowKeys.length} 条 </div>
                        <Button onClick={() => {
                            if (selectedRow.selectedRowKeys.length === 0) {
                                return notification.warn({
                                    message: '温馨提示',
                                    description: `请先选择要禁用的推广员`,
                                });
                            } else {
                                Modal.error({
                                    title: '确认禁用推广员',
                                    content: '确认批量禁用推广员',
                                    okText: '确认',
                                    onOk() {
                                        dispatch({
                                            type: 'promoter/fakeDisablePromoter',
                                            payload: { idList: selectedRow.selectedRowKeys.map(item => { return parseInt(item) }) },
                                            callback: () => {
                                                handleCallback()
                                                setSelectedRow({
                                                    ...selectedRow,
                                                    selectedRowKeys: [],

                                                })
                                            }
                                        })
                                    },
                                    onCancel() {
                                        console.log('Cancel');
                                    },
                                })
                            }
                        }}>批量禁用</Button>
                        <Button onClick={() => {
                            if (selectedRow.selectedRowKeys.length === 0) {
                                return notification.warn({
                                    message: '温馨提示',
                                    description: `请先选择要启用的推广员`,
                                });
                            } else {
                                Modal.error({
                                    title: '确认批量启用推广员',
                                    content: '确认批量启用推广员',
                                    okText: '确认',
                                    onOk() {
                                        dispatch({
                                            type: 'promoter/fakeEnablePromoter',
                                            payload: { idList: selectedRow.selectedRowKeys.map(item => { return parseInt(item) }) },
                                            callback: () => {
                                                handleCallback()
                                                setSelectedRow({
                                                    ...selectedRow,
                                                    selectedRowKeys: [],

                                                })
                                            }
                                        })
                                    },
                                    onCancel() {
                                        console.log('Cancel');
                                    },
                                })
                            }
                        }}>批量启用</Button>
                        <Button onClick={() => {
                            if (selectedRow.selectedRowKeys.length === 0) {
                                return notification.warn({
                                    message: '温馨提示',
                                    description: `请先选择要修改等级的推广员`,
                                });
                            } else {
                                setLevelVisible({
                                    show: true,
                                    selectIdList: selectedRow.selectedRowKeys.map(item => { return parseInt(item) })
                                })
                            }
                        }}>批量修改等级</Button>
                        <Button onClick={() => {
                            if (selectedRow.selectedRowKeys.length === 0) {
                                return notification.warn({
                                    message: '温馨提示',
                                    description: `请先选择要修改邀请人的推广员`,
                                });
                            } else {
                                setShareVisible({
                                    show: true,
                                    updateList: selectedRow.rowKeyList,
                                    selectIdList: selectedRow.selectedRowKeys.map(item => { return parseInt(item) })
                                })
                            }
                        }}>批量修改邀请人</Button>
                        <Button onClick={() => {
                            if (selectedRow.selectedRowKeys.length === 0) {
                                return notification.warn({
                                    message: '温馨提示',
                                    description: `请先选择要绑定的员工`,
                                });
                            } else {
                                setBindAssignVisible({
                                    show: true,
                                    detail: {},
                                    type: "all",
                                    selectIdList: selectedRow.selectedRowKeys.map(item => { return parseInt(item) })
                                })
                            }
                        }}>批量绑定员工</Button>
                        <Button onClick={() => {
                            if (selectedRow.selectedRowKeys.length === 0) {
                                return notification.warn({
                                    message: '温馨提示',
                                    description: `请先选择要绑定的员工`,
                                });
                            } else {
                                setPromoterVisible({
                                    show: true,
                                    detail: {},
                                    type: "all",
                                    selectIdList: selectedRow.selectedRowKeys.map(item => { return parseInt(item) })
                                })
                            }
                        }}>批量绑定分组</Button>
                    </Space>
                </Col>
                <Col span={24}>
                    <TableDataBlock
                        rowSelection={selectedRow}
                        cRef={childRef}
                        loading={loading}
                        params={params}
                        firstFetch={false}
                        columns={getColumns}
                        rowKey={(record) => `${record.id}`}
                        dispatchType="promoter/fetchListPromoter"
                        {...list}
                    ></TableDataBlock>
                </Col>

            </Row>
            <RoleSetForm
                childRef={childRef}
                visible={visible}
                onClose={() => setVisible(false)}
                handleCallback={handleCallback}
            ></RoleSetForm>
            <BindAssign
                cleanSelect={() => {
                    setSelectedRow({
                        ...selectedRow,
                        selectedRowKeys: [],
                    })
                }}
                visible={bindAssignVisible}
                onClose={() => setBindAssignVisible(false)}
                handleCallback={handleCallback}></BindAssign>

            <BankForm visible={bankVisible}
                onClose={() => setBankVisible(false)}
                handleCallback={handleCallback}></BankForm>
            <UpdateLevel
                cleanSelect={() => {
                    setSelectedRow({
                        ...selectedRow,
                        selectedRowKeys: [],
                    })
                }}
                promoterLevelList={promoterLevelList}
                visible={levelVisible}
                onClose={() => setLevelVisible(false)}
                handleCallback={handleCallback}
            ></UpdateLevel>
            {shareVisible && <UpdateShare
                cleanSelect={() => {
                    setSelectedRow({
                        ...selectedRow,
                        selectedRowKeys: [],
                        rowKeyList: []
                    })
                }}
                visible={shareVisible}
                onClose={() => setShareVisible(false)}
                handleCallback={handleCallback}
            ></UpdateShare>}
            <CodeModel visible={codeVisible} onClose={() => setCodeVisible(false)}></CodeModel>
            <CodeShare visible={initVisible} onClose={() => setInitVisible(false)}></CodeShare>
            <OriParentList visible={oriVisible} onClose={() => setOriVisible(false)}></OriParentList>
            <SelectPromoterGroup onChange={(e = {}) => {
                const { selectIdList } = promoterGroupVisible
                fakeSetGroupId({
                    idList: selectIdList,
                    ...e
                })
            }} type='radio' visible={promoterGroupVisible} onClose={() => setPromoterVisible(false)}></SelectPromoterGroup>
        </div>
    );
};

export default connect(({ promoter, loading }) => ({
    list: promoter.promoterList,
    loading: loading.models.promoter,
}))(PromoterList);
